<?php
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../_inc/funct.xbrlBil.php');
require_once('../_inc/funct.genPhpScript.php');
require_once('../../_inc/funct.tabDati.php');

$sSql = "SELECT sd.id_set_dati, sd.descr, sd.cod_set_dati "
	." FROM rgl_set_dati sd "
	." WHERE fonte_bil = 'xbrl01' "
	." ORDER BY sd.cod_set_dati";
$objDB->query($sSql,'selATD');
$aSD = array();
while($acSD = $objDB->fetch('selATD')) {
	reqDef('id_set_dati',$acSD['id_set_dati']);
	$aSD[$acSD['id_set_dati']] = $acSD['cod_set_dati']." - ".$acSD['descr'];
}
if (count($aSD)==0) {
	backOnErr('nessun set con fonte xbrl01');
}
$aInfo = null;
if (reqVar('azione') == 'carica') {
	$msgPag = caricaBil($aInfo);
} 

$sCmdR = '';
$sCmdR .= "<a class='cmd1' href='javascript:document.frm1.submit();'>carica</a>";
$sCmdR .= cmdTorna('torna');

testaHtml('', $msgPag, 'ratg');
?>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right">
			<? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo getHtmlForm('frm1','',array('enctype'=>true));
echo getHtmlHidden('azione','carica');
echo getHtmlHidden('xsn',XSN);
?>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<?=getHtmlRigaRif();?>
   <tr>
      <td class="tit1" colspan='20' align='center'>Acquisizione bilanci da file XBRL</td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Cod. CCIAA (ppnnnn)</td>
      <td class="txt1" colspan='3' align='left'>
      	<? echo getHtmlText('id_azienda', 16);?>
      </td>
      <td class="lab1" colspan='2' align='left'>Descrizione</td>
      <td class="txt1" colspan='11' align='left'>
      	<? echo getHtmlText('descr',100);?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='5' align='left'>Nota</td>
      <td class="txt1" colspan='15' align='left'>
      	<? echo getHtmlTextArea('nota', 100,5);?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Set dati</td>
      <td class="txt1" colspan='16' align='left'>
<? 
echo getHtmlSelect('id_set_dati', $aSD);
?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>File</td>
      <td class="txt1" colspan='16' align='left'>
      	<? echo getHtmlFile('file_xbrl', 80);?>
      </td>
   </tr>
   <tr>
      <td class="cmd1" align="right" colspan='20'>
         <? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo "</form>\n";

codaHtml();
exit();


function caricaBil(&$aInfo) {
	global $objDB,$objSess;
	$msg = '';
	$aInfo = null;
	//$_REQUEST['id_azienda'] = strtoupper(trim(reqVar('id_azienda')));
	//if (reqVar('id_azienda')=='') {
	//	$msg .= _t("Codice obbligatorio")."<br>";
	//}
	if (reqVarInt('id_set_dati')==0) {
		$msg .= _t("set dati obbligatorio")."<br>";
	}
	if ($msg != '') return $msg;
	
	$aInfo = array('anag'=>array(),'dati'=>array());
	
	if (!isset($_FILES['file_xbrl']) || $_FILES['file_xbrl']['tmp_name'] == '') {
		$msg .= "nessun file caricato<br>";
	}
	if ($msg!='') return $msg;
	$sXml = file_get_contents($_FILES['file_xbrl']['tmp_name']);
	//dbg_($_FILES['file_xbrl']['tmp_name']." - sXml=".htmlentities(substr($sXml,0,20)));
	
	$pos = strpos($sXml,'<?xml ');
	if ($pos===false) {
		return "File non conforme<br>";
	}
	
	$sSql = "SELECT d.* FROM rgl_def_dato d "
		." WHERE d.id_set_dati = ".reqVarInt('id_set_dati')
		." ORDER BY d.id_set_dati, d.seq, d.cod_dato ";
	//dbg_($sSql);
	$objDB->query($sSql,'selDefDati');
	$aDefDati = array();
	while($acDD=$objDB->fetch('selDefDati')) {
		$aDefDati[$acDD['cod_dato']] = $acDD;
	}
	//genera script php e livello calcolo
	
	genPhpScript($aDefDati);
	
	$sXml = substr($sXml,$pos);
	$msg .= xbrl01aInfo($aDefDati, $sXml, $aInfo);
	if (reqVarTrim('id_azienda')!='') {
		$aInfo['anag']['id_azienda'] = strtoupper(reqVarTrim('id_azienda'));
	}
	if ($msg!='') return $msg;
	
	//$aInfo=null; return "WIP";
	
	if (reqvarTrim('descr')=='') {
		$_REQUEST['descr'] = "Bilancio da file XBRL";
	}
	
	//inserisce/aggiorna anag 
	$sSql = "SELECT a.*  FROM rgl_azienda a "
		." WHERE a.cod_fisc = '".addslashes($aInfo['anag']['cod_fisc'])."'";
	$objDB->query($sSql, 'readBil');		
	if ($aAnag = $objDB->fetch('readBil')) {
		$idAzienda = $aAnag['id_azienda'];
		$sSql = "UPDATE rgl_azienda SET cod_cciaa = '".addslashes($aInfo['anag']['cod_cciaa'])."' "
			.",rag_soc = '".addslashes($aInfo['anag']['rag_soc'])."' "
			.",sede = '".addslashes($aInfo['anag']['comune'])."'"
			.",cod_fisc = '".addslashes($aInfo['anag']['cod_fisc'])."'"
			." WHERE id_azienda = ".$idAzienda
			;
		$objDB->query($sSql, 'insAzi');
	} else {
		$sSql = "INSERT INTO rgl_azienda SET cod_cciaa = '".addslashes($aInfo['anag']['cod_cciaa'])."' "
			.",rag_soc = '".addslashes($aInfo['anag']['rag_soc'])."' "
			.",sede = '".addslashes($aInfo['anag']['comune'])."'"
			.",cod_fisc = '".addslashes($aInfo['anag']['cod_fisc'])."'"
			;
		$objDB->query($sSql, 'insAzi');
		$idAzienda = $objDB->lastInsertId('insAzi');
	}
	
	foreach($aInfo['dati'] as $dataRif => $aDati) {
		$sSql = "SELECT *  FROM rgl_bilancio "
			." WHERE id_azienda = $idAzienda "
			." AND id_set_dati = ".reqVarInt('id_set_dati')
			." AND data_rif = '".addslashes($dataRif)."'";
		$objDB->query($sSql, 'readBil');		
		if (!$aRec=$objDB->fetch('readBil')) {
			$sSql = "INSERT INTO rgl_bilancio SET id_azienda = $idAzienda "
				.",fonte_bil = 'xbrl01' "
				.",data_rif = '$dataRif' "
				.",data_iniz = '".substr($dataRif,0,4)."-01-01' "
				.",id_set_dati = ".reqVarInt('id_set_dati')
				.",descr = '".reqVarAS('descr')."' "
				.",nota = '".reqVarAS('nota')."' "
				.",str_def_dati = '".asgzcser($aDefDati)."'"
				.",str_dati = '".asgzcser($aDati)."'"
				.",file_caricato = '".asgzc($sXml)."'"
				.",stato_lav = 'da verificare' "
				;
			$objDB->query($sSql, 'insBil');
			$idBil = $objDB->lastInsertId('insBil');
			$sSql = "INSERT INTO rgl_bilancio_log SET id_bil = $idBil "
				.",data_ora = '".date('Y-m-d H:i:s')."' "
				.",id_utente = ".intval($objSess->idUtente)
				.",descr_operaz = 'Caricato da XBRL' "
				.",str_dati = '".asgzcser($aDati)."'"
				;
			$objDB->query($sSql, 'insBil');
			$msg .= "caricato bilacio al $dataRif di ".$aInfo['anag']['rag_soc']."<br/>\n";
		} else {		
			$sSql = "UPDATE rgl_bilancio SET id_set_dati = ".reqVarInt('id_set_dati')
					.",str_def_dati = '".asgzcser($aDefDati)."'"
					.",str_dati = '".asgzcser($aDati)."'"
					.",file_caricato = '".asgzc($sXml)."'"
					.",fonte_bil = 'xbrl01' "
					.",descr = '".reqVarAS('descr')."' "
					.",nota = '".reqVarAS('nota')."' "
					.",stato_lav = 'da verificare' "
					." WHERE id_bil = ".$aRec['id_bil'];
			$objDB->query($sSql, 'updBil');
			$sSql = "INSERT INTO rgl_bilancio_log SET id_bil = ".$aRec['id_bil']
				.",data_ora = '".date('Y-m-d H:i:s')."' "
				.",id_utente = ".intval($objSess->idUtente)
				.",descr_operaz = 'Ri-caricato da XBRL' "
				.",str_dati = '".asgzcser($aDati)."'"
				;
			$objDB->query($sSql, 'updBil');
			$msg .= "ri-caricato bilacio al $dataRif di ".$aInfo['anag']['rag_soc']."<br/>\n";
		}
	}
	return $msg;
	exit();
}
